package com.sg.common.empty.web;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.sg.common.db.DbUtil;
import com.sg.common.empty.entity.Myinput;
import com.sg.common.empty.entity.PerfProperty;
import com.sg.common.empty.entity.Property;
import com.sg.common.empty.entity.TableBean;
import com.sg.common.empty.json.Filter;
import com.sg.common.empty.json.Nsecs;
import com.sg.common.empty.service.CfgService;
import com.sg.common.file.FileUtil;
import com.sg.common.http.HttpHelper;
import com.sg.common.utils.AssertUtils;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.ReUtils;
import com.sg.common.utils.SyncUtil;

@Repository
@Controller
public class TableBeanController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	final String SEPORATOR = System.getProperty("line.separator");
	final static String TAB = "\t";

	@Autowired
	HttpServletRequest request;

	@Autowired
	CfgService service;

	/**
	 * 将本地的数据库中某个Bean相关的数据，
	 * 如property、permission、perf、filter、filterProperty迁移到对方数据源
	 * 数据源必须已经在properties\jdbc中已经定义，不然取不到数据源
	 * 
	 * @param request
	 * @return
	 * @throws SQLException
	 * @throws InterruptedException 
	 */
	@RequestMapping(value = "/cfg/Bean/sendData")
	@ResponseBody
	public Object send(HttpServletRequest request) throws SQLException, InterruptedException {
		String ds = request.getParameter("_ds");
		String ids = request.getParameter("_ids");
		String[] idt = StringUtils.split(ids, ",");
		String oranConStr = "wwsms";
		for (String beanId : idt) {
			
			// bean
			String oranSelect = "select id,bean,descr,descrProperty,tablename,isFlow,className,pkg,usrct from cfg_bean where id='"
					+ beanId + "'";
			final String cusSelect = "select 1 from cfg_bean where id=?";
			final String cusUpdate = "update cfg_bean set bean=?,descr=?,descrProperty=?,tablename=?,isflow=?,classname=?,pkg=?,usrct=? where id=?";
			final String cusInsert = "insert into cfg_bean (id,bean,descr,descrProperty,tablename,isFlow,className,pkg,usrct) VALUES (?,?,?,?,?,?,?,?,?)";
			SyncUtil.syncOneWayTo(ds, oranConStr, oranSelect, cusSelect, cusUpdate,
					cusInsert);
			
			//property
			String oranSelect_prop = "select id,bean,descr,property,usrct,type,length,ord,width,votype,myinput,required,valueurl,validtype,dftvalue,min,max,showvalue from cfg_property where bean='"
					+ beanId + "'";
			final String cusSelect_prop = "select 1 from cfg_property where id=?";
			final String cusUpdate_prop = "update cfg_property set bean=?,descr=?,property=?,usrct=?,type=?,length=?,ord=?,width=?,votype=?,myinput=?,required=?,valueurl=?,validtype=?,dftvalue=?,min=?,max=?,showvalue=? where id=?";
			final String cusInsert_prop = "insert into cfg_property (id,bean,descr,property,usrct,type,length,ord,width,votype,myinput,required,valueurl,validtype,dftvalue,min,max,showvalue) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			SyncUtil.syncOneWayTo(ds, oranConStr, oranSelect_prop, cusSelect_prop, cusUpdate_prop,
					cusInsert_prop);
			
			//permission
			TableBean tableBean = service.get(TableBean.class,beanId);
			String oranSelect_per = "select id,uri0,uri1,uri2,canin,parent,fullDescr,descr,type,enable,open,perf,usrct from cfg_permission where uri0='"
					+ tableBean.getPkg() + "' and uri1='"+tableBean.getBean()+"'";
			final String cusSelect_per = "select 1 from cfg_permission where id=?";
			final String cusUpdate_per = "update cfg_permission set uri0=?,uri1=?,uri2=?,canin=?,parent=?,fullDescr=?,descr=?,type=?,enable=?,open=?,perf=?,usrct=? where id=?";
			final String cusInsert_per = "insert into cfg_permission (id,uri0,uri1,uri2,canin,parent,fullDescr,descr,type,enable,open,perf,usrct) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
			SyncUtil.syncOneWayTo(ds, oranConStr, oranSelect_per, cusSelect_per, cusUpdate_per,
					cusInsert_per);
			
			//perf
			String oranSelect_perf = "select id,bean,permission,descr,kind,ord,perf,layout,usrct from cfg_perf where bean='"
					+ beanId +"'";
			final String cusSelect_perf = "select 1 from cfg_perf where id=?";
			final String cusUpdate_perf = "update cfg_perf set bean=?,permission=?,descr=?,kind=?,ord=?,perf=?,layout=?,usrct=? where id=?";
			final String cusInsert_perf = "insert into cfg_perf (id,bean,permission,descr,kind,ord,perf,layout,usrct) VALUES (?,?,?,?,?,?,?,?,?)";
			SyncUtil.syncOneWayTo(ds, oranConStr, oranSelect_perf, cusSelect_perf, cusUpdate_perf,
					cusInsert_perf);
			
			//filter
			String oranSelect_filter = "select id,permission,func,params,descr,ord,usrct,permission_id from cfg_filter where permission in (select id from cfg_permission where uri0='"
					+ tableBean.getPkg() + "' and uri1='"+tableBean.getBean()+"')";
			final String cusSelect_filter = "select 1 from cfg_filter where id=?";
			final String cusUpdate_filter = "update cfg_filter set permission=?,func=?,params=?,descr=?,ord=?,usrct=?,permission_id=? where id=?";
			final String cusInsert_filter = "insert into cfg_filter (id,permission,func,params,descr,ord,usrct,permission_id) VALUES (?,?,?,?,?,?,?,?)";
			SyncUtil.syncOneWayTo(ds, oranConStr, oranSelect_filter, cusSelect_filter, cusUpdate_filter,
					cusInsert_filter);
			
			//filterProp
			String oranSelect_filterProp = "select id,filter,property,op,val,clazz,usrct,filter_id,property_id from cfg_filter_property where filter in (select id from cfg_filter where permission in (select id from cfg_permission where uri0='"
					+ tableBean.getPkg() + "' and uri1='"+tableBean.getBean()+"'))";
			final String cusSelect_filterProp = "select 1 from cfg_filter_property where id=?";
			final String cusUpdate_filterProp = "update cfg_filter_property set filter=?,property=?,op=?,val=?,clazz=?,usrct=?,filter_id=?,property_id=? where id=?";
			final String cusInsert_filterProp = "insert into cfg_filter_property (id,filter,property,op,val,clazz,usrct,filter_id,property_id) VALUES (?,?,?,?,?,?,?,?,?)";
			SyncUtil.syncOneWayTo(ds, oranConStr, oranSelect_filterProp, cusSelect_filterProp, cusUpdate_filterProp,
					cusInsert_filterProp);
		}
		return "成功";
	}

	/**
	 * 按钮：创建动态文件
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/cfg/bean/dymVo", method = RequestMethod.POST)
	@ResponseBody
	public Object dymVo(HttpServletRequest request) {
		// TODO
		// 根据bean找到对应的property，从而生成hbm文件

		// 找到entity文件夹，写入文件
		// 返回成功

		return null;
	}

	// @RequestMapping(value = "/acti/common/complete", method =
	// RequestMethod.POST)
	// @ResponseBody
	public Object complete(HttpServletRequest request)
			throws NoSuchFieldException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			IllegalArgumentException, SecurityException,
			ClassNotFoundException, InstantiationException {
		// 用于业务系统更新Bean信息
		String beanId = request.getParameter("beanId");
		String className = request.getParameter("className");

		// 提交至流程系统进行处理
		String taskIds = request.getParameter("taskIds");
		String checkAdvice = request.getParameter("checkAdvice");
		String isAgree = request.getParameter("isAgree");

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("checkAdvice", checkAdvice));
		params.add(new BasicNameValuePair("isAgree", isAgree));
		@SuppressWarnings("unchecked")
		Map<String, String> response = (Map<String, String>) HttpHelper
				.httpPost_nv("http://10.10.38.15:8081/NKBMS/complete/"
						+ taskIds + "", params);

		return response;
	}

//	@RequestMapping(value = { "/cfg/bean/add", "/cfg/Bean/add" }, method = RequestMethod.POST)
//	@ResponseBody
//	public Object add(HttpServletRequest request) throws NoSuchFieldException,
//			IllegalAccessException, InvocationTargetException,
//			NoSuchMethodException, IllegalArgumentException, SecurityException,
//			ClassNotFoundException, InstantiationException, SQLException {
//
//		Object bean = request.getAttribute("bean");
//		Perf perf = (Perf) request.getAttribute("perf");
//		String layout = perf.getLayout();
//		Nsecs ne = JSON.parseObject(layout, Nsecs.class);
//		if (StringUtils.equals("nadd", perf.getKind())) {
//			List<PerfProperty> pps = service.ppsInSecTables(bean, ne);
//			AssertUtils.notNull(bean, "保存对象不能为空");
//			Filter filter = (Filter) request.getAttribute("filter");
//			Object forSave = bean.getClass().newInstance();
//			for (PerfProperty pp : pps) {
//				ReUtils.copyValue(bean, forSave, pp.getProperty().getProperty());
//			}
//			service.beforeSave(forSave, filter, request);
//			service.save(forSave);
//			// if (bean.getClass().equals(TableBean.class)) {
//			add_bean(request, forSave);
//			// }
//			String body = com.sg.common.utils.Constant.get("ADD_SUCCESS")
//					+ " <a href='"
//					+ request.getRequestURI().replace("add", "edit")
//					+ "?_isp=1&id=" + ReUtils.get(forSave, "id") + "'>编辑页面</a>";
//			return body;
//		}
//		return "error";
//	}

	public String add_bean(HttpServletRequest request, Object bean)
			throws IllegalArgumentException, SecurityException,
			IllegalAccessException, ClassNotFoundException,
			NoSuchFieldException, SQLException, InstantiationException,
			InvocationTargetException, NoSuchMethodException {
		TableBean tBean = (TableBean) bean;

		Property idp = new Property();
		idp.setBean(tBean);
		idp.setDescr("ID");
		idp.setProperty("id");
		idp.setType("varchar");
		idp.setLength("32");
		service.save(idp);

		if (tBean.getIsFlow() != null && tBean.getIsFlow().equals("1")) {
			Property taskidp = new Property();
			taskidp.setBean(tBean);
			taskidp.setDescr("任务号");
			taskidp.setProperty("taskId");
			taskidp.setType("varchar");
			taskidp.setLength("50");
			service.save(taskidp);

			Property taskkeyp = new Property();
			taskkeyp.setBean(tBean);
			taskkeyp.setDescr("任务Key");
			taskkeyp.setProperty("taskKey");
			taskkeyp.setType("varchar");
			taskkeyp.setLength("50");
			service.save(taskkeyp);

			Property proinsidp = new Property();
			proinsidp.setBean(tBean);
			proinsidp.setDescr("流程实例ID");
			proinsidp.setProperty("proInsId");
			proinsidp.setType("varchar");
			proinsidp.setLength("50");
			service.save(proinsidp);
		}

		Property enabledp = new Property();
		enabledp.setBean(tBean);
		enabledp.setDescr("有效?");
		enabledp.setProperty("enable");
		enabledp.setType("varchar");
		enabledp.setLength("2");
		Myinput radio = new Myinput();
		radio.setId("15");
		enabledp.setMyinput(radio);
		enabledp.setDftvalue("1");
		enabledp.setShowvalue("enable");
		enabledp.setWidth("50");
		enabledp.setOrd(90);
		service.save(enabledp);

		Property cddp = new Property(tBean, "createDate", "varchar", "创建日期",
				"20", 90, "100");
		service.save(cddp);

		Property cmdp = new Property(tBean, "createMember", "varchar", "创建人",
				"32", 90, "50");
		cmdp.setVotype("com.sg.common.cfg.entity.Member");
		service.save(cmdp);

		// Property cmiddp = new Property((TableBean) bean, "createMember.id",
		// "",
		// "创建人ID", "", 90, "80");
		// service.save(cmiddp);
		// Property cmdescrdp = new Property((TableBean) bean,
		// "createMember.descr", "", "创建人描述", "", 90, "80");
		// service.save(cmdescrdp);

		Property uddp = new Property(tBean, "updateDate", "varchar", "更新日期",
				"20", 90, "100");
		service.save(uddp);

		Property umdp = new Property(tBean, "updateMember", "varchar", "更新人",
				"32", 90, "50");
		umdp.setVotype("com.sg.common.cfg.entity.Member");
		service.save(umdp);

		// Property umiddp = new Property((TableBean) bean, "updateMember.id",
		// "",
		// "更新人ID", "", 90, "80");
		// service.save(umiddp);
		// Property umdescrdp = new Property((TableBean) bean,
		// "updateMember.descr", "", "更新人描述", "", 90, "80");
		// service.save(umdescrdp);
		int ind = 0;
		while (ind < 10) {
			Property wdp = new Property();
			wdp.setBean(tBean);
			wdp.setDescr("扩展" + ind);
			wdp.setProperty("ws" + ind);
			wdp.setType("varchar");
			wdp.setLength("255");
			wdp.setOrd(99);
			service.save(wdp);
			ind++;
		}

		Property usrct = new Property(tBean, "usrct", "varchar", "用户端", "4",
				99, "");
		service.save(usrct);
		String body = Constant.get("ADD_SUCCESS") + " <a href='"
				+ request.getRequestURI().replace("add", "edit")
				+ "?_isp=1&bean.id=" + ReUtils.get(bean, "id") + "'>编辑页面</a>";
		return body;
	}

//	@RequestMapping(value = "/cfg/bean/tree")
//	@ResponseBody
//	public Object tree() throws SQLException, SecurityException,
//			IllegalArgumentException, NoSuchFieldException,
//			IllegalAccessException {
//		return beanTree(request.getParameter("id"));
//	}
//
//	private List<AsyncTree> beanTree(String id) {
//		List<AsyncTree> res = new ArrayList<AsyncTree>();
//		if (StringUtils.isEmpty(id)) {
//			DetachedCriteria dc = DetachedCriteria.forClass(TableBean.class);
//			List<TableBean> bl = service.find(dc);
//			List<String> sl = new ArrayList<String>();
//			for (TableBean b : bl) {
//				if (!sl.contains(b.getPkg())) {
//					sl.add(b.getPkg());
//				}
//			}
//			for (String s : sl) {
//				AsyncTree at = new AsyncTree();
//				at.setId("pkg:" + s);
//				at.setText(s);
//				at.setState("open");
//				at.setChildren(beanTree("pkg:" + s));
//				res.add(at);
//			}
//		} else if (id.startsWith("pkg:")) {
//			DetachedCriteria dc = DetachedCriteria.forClass(TableBean.class);
//			dc.add(Restrictions.eq("pkg", id.replace("pkg:", "")));
//			List<TableBean> bl = service.find(dc);
//			for (TableBean b : bl) {
//				AsyncTree at = new AsyncTree();
//				at.setId(String.valueOf(b.getId()));
//				at.setText(b.getBean() + ":" + b.getDescr());
//				at.setState("open");
//				res.add(at);
//			}
//		}
//		return res;
//	}

	@RequestMapping(value = "/cfg/bean/createdb")
	@ResponseBody
	@Transactional
	public Object createdb(HttpServletRequest request) throws SQLException,
			IllegalArgumentException, IllegalAccessException {
		String id = request.getParameter("id");
		if (!StringUtils.isNotEmpty(id) || StringUtils.equals(id, "null")) {
			return "";
		}
		TableBean bean = service.get(TableBean.class, id);
		DetachedCriteria dc = DetachedCriteria.forClass(Property.class);
		dc.add(Restrictions.eq("bean", bean));
		dc.addOrder(Order.asc("ord"));
		List<Property> pl = service.find(dc);
		String tableName = bean.getTableName();
		StringBuilder createSQL = createSQL(pl, tableName);
		// Connection con = DbUtil.flydymCon();
		Connection con = DbUtil.wwsmsCon();
		PreparedStatement ps = con
				.prepareStatement("SET FOREIGN_KEY_CHECKS=0;");
		ps = con.prepareStatement("DROP TABLE IF EXISTS `" + tableName + "`");
		ps.execute();
		ps = con.prepareStatement(createSQL.toString());
		ps.execute();
		ps.close();
		con.close();
		String body = "数据表创建完成！执行语句为：  " + createSQL;
		return body;
	}

	private StringBuilder createSQL(List<Property> pl, final String tableName) {
		StringBuilder tableBuilder = new StringBuilder();
		tableBuilder.append("CREATE TABLE `").append(tableName).append("` (");
		for (Property property : pl) {
			String propertyName = property.getProperty();
			if (!propertyName.contains(".")) {
				tableBuilder.append(SEPORATOR).append("`").append(propertyName)
						.append("` ").append(property.getType()).append("(")
						.append(property.getLength()).append(") ");
				if ("id".equals(propertyName)) {
					tableBuilder.append("NOT NULL,");
				} else {
					tableBuilder.append("DEFAULT NULL,");
				}
			}
		}
		if (!CollUtil.isNotEmpty(pl)) {
			tableBuilder.append("`id` varchar(32) NOT NULL,");
		}
		tableBuilder.append(SEPORATOR).append("PRIMARY KEY (`id`))")
				.append(SEPORATOR).append("ENGINE=InnoDB DEFAULT CHARSET=utf8");
		return tableBuilder;
	}
//
//	@RequestMapping(value = "/cfg/bean/createpermission")
//	@ResponseBody
//	@Transactional
//	public Object cp() throws IllegalAccessException,
//			InvocationTargetException, NoSuchMethodException {
//		// 获取tablebean
//		Object bean = request.getAttribute("bean");
//		TableBean one = (TableBean) service.get(bean.getClass(),
//				ReUtils.getStr(bean, "id"));
//		String pkg = one.getPkg();
//		String beanName = one.getBean();
//
//		// 删除已经有的相关权限与页面
//		DetachedCriteria dc = DetachedCriteria.forClass(Permission.class);
//		dc.add(Restrictions.eq("uri0", pkg))
//				.add(Restrictions.eq("uri1", beanName).ignoreCase())
//				.add(Restrictions.in("uri2", new String[] { "find", "edit",
//						"batchEdit", "detail", "add", "tree", "del", "exp",
//						"select", "" }));
//		List<Permission> permissionToDel = service.find(dc);
//		if (CollUtil.isNotEmpty(permissionToDel)) {
//			dc = DetachedCriteria.forClass(Perf.class);
//			dc.add(Restrictions.in("permission", permissionToDel));
//			List<Perf> perfs = service.find(dc);
//			dc = DetachedCriteria.forClass(RolePermission.class);
//			dc.add(Restrictions.in("permission", permissionToDel));
//			List<RolePermission> rps = service.find(dc);
//			dc = DetachedCriteria.forClass(RolePerf.class);
//			dc.add(Restrictions.in("perf", perfs));
//			List<RolePerf> rperfs = service.find(dc);
//			service.deleteList(rperfs);
//			service.deleteList(perfs);
//			service.deleteList(rps);
//			service.deleteList(permissionToDel);
//		}
//
//		// 获取属性列表
//		DetachedCriteria ddc = DetachedCriteria.forClass(Property.class);
//		ddc.add(Restrictions.eq("bean", one));
//		ddc.addOrder(Order.asc("ord"));
//		List<Property> propertyList = service.find(ddc);
//		StringBuilder propertyAll = new StringBuilder();
//		StringBuilder propertyInput = new StringBuilder();
//		for (Property prop : propertyList) {
//			String pn = prop.getProperty();
//			propertyAll.append(pn).append(",");
//			if (prop.getMyinput() != null) {
//				propertyInput.append(pn).append(",");
//			}
//		}
//		if (StringUtils.isNotEmpty(propertyAll.toString())) {
//			propertyAll.deleteCharAt(propertyAll.length() - 1);
//		}
//		if (StringUtils.isNotEmpty(propertyInput.toString())) {
//			propertyInput.deleteCharAt(propertyInput.length() - 1);
//		}
//		// type3权限
//		ddc = DetachedCriteria.forClass(Permission.class);
//		ddc.add(Restrictions.eq("type", "3")).add(Restrictions.eq("uri0", pkg));
//		Permission p3 = service.findBean(ddc);
//		if (p3 == null) {
//			p3 = Permission.create(pkg, null, "", "", "", "3");
//			service.save(p3);
//		}
//		// type2权限
//		Permission p2 = Permission.create(pkg, p3, beanName, "",
//				one.getDescr(), "2");
//		service.save(p2);
//
//		// find权限
//		Permission pf = Permission.create(pkg, p2, beanName, "find",
//				one.getDescr(), "1");
//		service.save(pf);
//		StringBuilder findLayout = new StringBuilder();
//		findLayout.append("{\"search\":[{\"pn\":\"").append(propertyInput)
//				.append("\"}],\"list\":[{\"pn\":\"").append(propertyAll)
//				.append("\"}],\"sort\":\"id\",\"order\":\"desc\"}");
//		service.save(Perf.create(one, pf, "list", findLayout.toString()));
//
//		// add权限
//		Permission pa = Permission.create(pkg, p2, beanName, "add", "增加", "0");
//		service.save(pa);
//		StringBuilder addlayout = new StringBuilder();
//		addlayout.append("{\"enctype\":\"\",\"sts\":[{\"title\":\"")
//				.append("增加-" + one.getDescr())
//				.append("\",\"props\":[{\"pn\":\"")
//				.append(propertyInput.toString()).append("\"}]}]}");
//		service.save(Perf.create(one, pa, "nadd", addlayout.toString()));
//
//		// edit权限
//		Permission pe = Permission.create(pkg, p2, beanName, "edit", "修改", "0");
//		service.save(pe);
//		StringBuilder editlayout = new StringBuilder();
//		editlayout
//				.append("{\"enctype\":\"\",\"sts\":[{\"title\":\"")
//				.append("修改-" + one.getDescr())
//				.append("\",\"props\":[{\"pn\":\"id\",\"esh\":\"0\"},{\"pn\":\"")
//				.append(propertyInput.toString()).append("\"}]}]}");
//		service.save(Perf.create(one, pe, "nedit", editlayout.toString()));
//
//		// batchEdit权限
//		Permission pbe = Permission.create(pkg, p2, beanName, "batchEdit",
//				"批量修改", "0");
//		service.save(pbe);
//		StringBuilder batchEditlayout = new StringBuilder();
//		batchEditlayout
//				.append("{\"enctype\":\"\",\"sts\":[{\"title\":\"")
//				.append("批量修改-" + one.getDescr())
//				.append("\",\"props\":[{\"pn\":\"id\",\"esh\":\"0\"},{\"pn\":\"")
//				.append(propertyInput.toString()).append("\"}]}]}");
//		service.save(Perf.create(one, pbe, "nedit", batchEditlayout.toString()));
//
//		// detail权限
//		Permission pd = Permission.create(pkg, p2, beanName, "detail", "详细",
//				"0");
//		service.save(pd);
//		StringBuilder detaillayout = new StringBuilder();
//		detaillayout.append("{\"sts\":[{\"title\":\"")
//				.append("详细-" + one.getDescr())
//				.append("\",\"props\":[{\"pn\":\"")
//				.append(propertyAll.toString()).append("\"}]}]}");
//		service.save(Perf.create(one, pd, "ndetail", detaillayout.toString()));
//
//		List<Permission> pl = new ArrayList<Permission>();
//		Permission pdel = Permission
//				.create(pkg, p2, beanName, "del", "删除", "0");
//		service.save(pdel);
//		pl.add(pdel);
//		Permission pexp = Permission
//				.create(pkg, p2, beanName, "exp", "导出", "0");
//		service.save(pexp);
//		StringBuilder expLayout = new StringBuilder();
//		expLayout.append("{\"search\":[{\"pn\":\"").append(propertyInput)
//				.append("\"}],\"list\":[{\"pn\":\"").append(propertyAll)
//				.append("\"}]}");
//		service.save(Perf.create(one, pexp, "nexp", expLayout.toString()));
//
//		//pl.add(pexp);
//		Permission p_tree = Permission.create(pkg, p2, beanName, "tree", "树",
//				"-1");
//		service.save(p_tree);
//		pl.add(p_tree);
//		Permission p_select = Permission.create(pkg, p2, beanName, "select",
//				"选择", "-1");
//		service.save(p_select);
//		pl.add(p_select);
//
//		// 添加Permission对应的Perf
//		for (Permission permission : pl) {
//			// 对需要的Permission进行添加
//			service.save(Perf.create(one, permission, "", ""));
//		}
//		String basePath = request.getScheme() + "://" + request.getServerName()
//				+ ":" + request.getServerPort() + request.getContextPath()
//				+ "/";
//		return "<a href='" + basePath
//				+ "cfg/role/find?_isp=1'>权限配置</a><a href='" + basePath
//				+ pf.uri() + "?_isp=1'>go test</a>";
//	}

	/*
	 * 创建VO文件
	 */
	@RequestMapping(value = "/cfg/bean/createvo")
	@ResponseBody
	@Transactional
	public Object cv() throws IOException, ClassNotFoundException,
			InstantiationException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		// 获取tablebean
		Object bean = request.getAttribute("bean");
		TableBean one = (TableBean) service.get(bean.getClass(),
				ReUtils.getStr(bean, "id"));
		String className = one.getClassName();
		DetachedCriteria dc = DetachedCriteria.forClass(Property.class);
		dc.add(Restrictions.eq("bean", bean));
		dc.addOrder(Order.asc("ord"));
		List<Property> pl = service.find(dc);
		String pkg = one.getPkg();
		String beanName = one.getBean();
		String tableName = one.getTableName();
		String tableDescr = one.getDescr();
		if (StringUtils.startsWith(className, "com.sg.dym")) {
			// 动态则生成HBM文件即可
			String dymFileName = pkg + "_" + beanName + ".hbm.xml";

			StringBuilder dymFileContent = createdym(pl, tableName, className,
					tableDescr);
			// 创建文件，并返回文件名
			String sorceFolder = Constant.getPorjectPath()
					+ "/WEB-INF/classes/entity/";
			createFile2(dymFileContent, dymFileName, sorceFolder);

		} else {// 非动态生成java
			String voFileName = beanName + ".java";
			StringBuilder voFileContent = createVo(pl, beanName, tableName,
					pkg, tableDescr,className);
			// 创建文件，并返回文件名
			String sorceFolder = Constant.getPorjectPath() + "/upload/";
			createFile2(voFileContent, voFileName, sorceFolder);
		}
		return "ok";
	}

	private StringBuilder createVo(List<Property> pl, final String beanName,
			final String tableName, final String pkg, final String tableDescr, String className) {
		StringBuilder vo = new StringBuilder();
		int lastPoint = StringUtils.lastIndexOf(className, ".");
		vo.append("package ").append(StringUtils.substring(className, 0, lastPoint))
				.append(";")
				.append(SEPORATOR).append("import javax.persistence.Entity;")
				.append(SEPORATOR)
				.append("import javax.persistence.FetchType;")
				.append(SEPORATOR)
				.append("import javax.persistence.JoinColumn;")
				.append(SEPORATOR)
				.append("import javax.persistence.ManyToOne;")
				.append(SEPORATOR)
				.append("import com.sg.common.cfg.entity.BaseTO;")
				.append(SEPORATOR).append("import javax.persistence.Table;")
				.append(SEPORATOR).append("@Entity").append(SEPORATOR)
				.append("@Table(name = \"").append(tableName).append("\")")
				.append(SEPORATOR).append("/** ").append(tableDescr)
				.append("  */").append(SEPORATOR).append("public class ")
				.append(beanName).append(" extends BaseTO{");
		for (Property property : pl) {
			if (property.getProperty().equals("id"))
				continue;
			final String type = property.getType();
			final String propertyDescr = property.getDescr();
			if (StringUtils.isNotEmpty(type)) {
				vo.append(SEPORATOR).append(TAB).append("/** ")
						.append(propertyDescr).append("  */").append(SEPORATOR)
						.append(TAB).append("public ");
				String votype = property.getVotype();
				if (!StringUtils.isNotEmpty(votype)) {
					if ("int".equals(type)) {
						votype = "int";
					} else if ("varchar".equals(type)) {
						votype = "String";
					} else if ("text".equals(type)) {
						votype = "String";
					}
				}
				final String propertyName = property.getProperty();

				vo.append(votype).append(" ").append(propertyName);
				if ("String".equals(votype)) {
					if (StringUtils.equals(propertyName, "enable"))
						vo.append("=\"1\"");
					else
						vo.append("=\"\"");
				}
				vo.append(";");
				if (!"String".equals(votype) && !"int".equals(votype)) {
					vo.append(SEPORATOR).append(TAB)
							.append("@ManyToOne(fetch=FetchType.EAGER)")
							.append(SEPORATOR).append(TAB)
							.append("@JoinColumn(name = \"")
							.append(propertyName).append("\")");
				}
				final char charAt = propertyName.charAt(0);
				String c = String.valueOf(charAt);
				vo.append(SEPORATOR).append(TAB).append("public ")
						.append(votype).append(" ").append("get")
						.append(propertyName.replaceFirst(c, c.toUpperCase()))
						.append("(){return this.").append(propertyName)
						.append(";}");
				vo.append(SEPORATOR).append(TAB).append("public void set")
						.append(propertyName.replaceFirst(c, c.toUpperCase()))
						.append("(").append(votype).append(" one){this.")
						.append(propertyName).append("=one;}");
			}
		}
		vo.append(SEPORATOR).append("}");
		return vo;
	}

	private StringBuilder createdym(List<Property> pl, final String tableName,
			final String beanClassName, final String tableDescr) {
		StringBuilder hib = new StringBuilder();
		hib.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
				.append(SEPORATOR)
				.append("<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"")
				.append(SEPORATOR)
				.append("\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">")
				.append(SEPORATOR).append("<hibernate-mapping>")
				.append(SEPORATOR).append(TAB).append("<!-- ")
				.append(tableDescr).append(" -->").append(SEPORATOR)
				.append(TAB).append("<class entity-name=\"")
				.append(beanClassName).append("\" table=\"").append(tableName)
				.append("\">")

		;
		for (Property property : pl) {
			final String type = property.getType();
			String votype = property.getVotype();
			if (StringUtils.isNotEmpty(type)) {
				final String propertyName = property.getProperty();
				final String propertyDescr = property.getDescr();
				if ("id".equals(propertyName)) {
					hib.append(SEPORATOR)
							.append(TAB)
							.append(TAB)
							.append("<id name=\"id\" type=\"string\" length=\"32\"><generator class=\"uuid.hex\" /></id>");
				} else {
					// String votype=property.getVotype();
					if (StringUtils.isNotEmpty(votype)) {
						hib.append(SEPORATOR)
								.append(TAB)
								.append(TAB)
								.append("<!-- ")
								.append(propertyDescr)
								.append(" -->")
								.append(SEPORATOR)
								.append(TAB)
								.append(TAB)
								.append("<many-to-one name=\"")
								.append(propertyName)
								.append("\" class=\"")
								.append(votype)
								.append("\" not-null=\"false\" lazy=\"false\" fetch=\"join\" not-found=\"ignore\"></many-to-one>");
					} else {
						if (!StringUtils.isNotEmpty(votype)) {
							if ("int".equals(type)) {
								votype = "int";
							} else if ("varchar".equals(type)) {
								votype = "string";
							} else if ("text".equals(type)) {
								votype = "string";
							}
						}
						hib.append(SEPORATOR).append(TAB).append(TAB)
								.append("<!-- ").append(propertyDescr)
								.append(" -->").append(SEPORATOR).append(TAB)
								.append(TAB).append("<property name=\"")
								.append(propertyName).append("\" column=\"")
								.append(propertyName).append("\" length=\"")
								.append(property.getLength())
								.append("\" type=\"").append(votype)
								.append("\"/>");
					}
				}
			}
		}
		hib.append(SEPORATOR).append(TAB).append("</class>").append(SEPORATOR)
				.append("</hibernate-mapping>");
		return hib;
	}

	private String createFile2(StringBuilder tableBuilder,
			final String fileName, String path) {
		byte tb[] = tableBuilder.toString().getBytes();
		InputStream tbis = new ByteArrayInputStream(tb);
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		File file = new File(path + fileName);
		FileUtil.inputstreamToFile(tbis, file);
		return path + fileName;
	}
}
